<?php defined('SYSPATH') or die('No direct script access.');

/**
 * Created by PhpStorm.
 * Author: daisc
 * QQ: 2444329889
 * Time: 2018/01/11 14:28
 * Desc: 任务调用类
 */
class St_Task
{

    /**
     * @function 计划任务初始化,需要执行的时间
     * Cron::set($name, array($frequency, $callback))
     */
    public static function init()
    {
        //订单取消任务
        Cron::set('order_cancel', array('* * * * *', 'St_Task::cancel_order'));

        //支付后确认超时退款
        Cron::set('refund_order', array('* * * * *', 'St_Task::refund_order'));

        //订单自动完成任务(每晚9:30执行一次)
        Cron::set('order_complete', array('* * * * *', 'St_Task::complete_order'));

        Cron::set('sms_num_short_hint', array('30 16 * * *', 'St_Task::sms_num_short_hint'));

        Cron::set('search_transfer_weixin', array('*/5 * * * *', 'St_Task::search_transfer_weixin'));

        /**
         * 模块自定义配置定时任务，模块下config文件夹添加crontab.php配置文件，键名需要保证唯一。
         * 格式：
         * return array(
         *     'together_expire_check'=> array('* * * * *', 'Model_Together_Join::together_expire')
         * );
         */
        $crontab = Kohana::$config->load('crontab');

        if(Arr::is_array($crontab))
        {
            foreach($crontab as $cron_name=>$cron)
            {
               Cron::set($cron_name, $cron);
            }
        }
        Cron::run();
    }

    /**
     * @function 订单取消任务.
     */
    public static function cancel_order()
    {
        //订单未付款,过期时间大于当前时间的订单
        $order_list = DB::select()->from('member_order')
            ->where('auto_close_time', '>', 0)
            ->and_where('auto_close_time', '<', time())
            ->and_where('status', '=', 1)
            ->execute()
            ->as_array();
        foreach ($order_list as $order) {
            $data = array(
                'status' => 3
            );
            $flag = DB::update('member_order')->set($data)->where('id', '=', $order['id'])->execute();
            if ($flag) {
                $order['status'] = 3;
                $model           = DB::select('maintable')->from('model')->where('id', '=', $order['typeid'])->execute()->get('maintable');
                if ($model) {
                    $product_model = "Model_" . ucfirst($model);
                }
                if ($product_model) {
                    Model_Member_Order::back_order_status_changed(1, $order, $product_model);
                }
            }
        }
    }

    /**
     * 支付后确认超时退款
     * @return void
     */
    public static function refund_order(){
        $order_list = DB::select()
            ->from('member_order')
            ->where('status', '=', 0)
            ->and_where('ispay', '=', 1)
            ->and_where('auto_confirm_time', '<', time())
            ->and_where('auto_confirm_time', '>', 0)
            ->and_where('online_transaction_no', '!=', '')
            ->execute()
            ->as_array();
        foreach ($order_list as $order) {
            $refund_data = array(
                'refund_reason' => '订单超过待确认时限，自动退款',
                'refund_platform' => '系统自动退款',
            );
            $model_info = Model_Model::get_module_info($order['typeid']);
            $maintable = $model_info['maintable'];
            $pieces = explode('_',$maintable);
            foreach($pieces as $key=>$piece) {
                $pieces[$key] = ucfirst($piece);
            }
            $class_name = 'Model_'.implode('_',$pieces);
            $refund_result = Pay_Online_Refund::refund_start($order['ordersn'],$class_name,false,$refund_data,0);
            St_Functions::writeLog($refund_result,__LINE__,'自动退款.log');
        }
    }

    /**
     * 订单自动完成
     */
    public static function complete_order()
    {
        // 使用日期加上后台设置的自动过期时间 小于当前时间 订单自动完成
        $configModel = new Model_Sysconfig();
        $res         = $configModel->getConfig(0);
        $auto_time   = $res['cfg_order_auto_finish_time'];
        if (!$auto_time) {
            return false;
        }
        $order_auto_finish_time = time() - intval($auto_time) * 86400;
        $sql                    = "SELECT * FROM `sline_member_order` WHERE status=2 and typeid not in(21,23,118,121) and unix_timestamp(usedate) <" . $order_auto_finish_time;
        $order_list             = DB::query(1, $sql)->execute()->as_array();

        foreach ($order_list as $order) {
            $data = array(
                'status' => 5
            );
            $flag = DB::update('member_order')->set($data)->where('id', '=', $order['id'])->execute();
            if ($flag) {
                $order['status'] = 5;
                $product_model   = St_Product::get_product_model($order['typeid']);
                if ($product_model) {
                    Model_Member_Order::back_order_status_changed(2, $order, $product_model);
                }
            }
        }
    }

    //短信不足提醒，仅适用于思途短信
    public static function sms_num_short_hint()
    {
        require_once TOOLS_COMMON . 'sms/smsservice.php';
        $hint_configs  = Model_Sysconfig::get_configs(0, array('cfg_sms_number_short_hint_open', 'cfg_sms_number_short_hint_min', 'cfg_sms_number_short_hint_admin_id', 'cfg_webname'));
        $admin         = DB::select()->from('admin')->where('id', '=', $hint_configs['cfg_sms_number_short_hint_admin_id'])->execute()->current();
        $min_short_num = intval($hint_configs['cfg_sms_number_short_hint_min']);
        if ($hint_configs['cfg_sms_number_short_hint_open'] != '1' || $min_short_num <= 0 || empty($admin) || empty($admin['phone'])) {
            return;
        }

        $provider = DB::select()->from('sms_provider')->where('execute_classname', '=', 'StourSMSProvider')->and_where('isopen', '=', 1)->execute()->current();
        if (empty($provider)) {
            return;
        }
        $provider_instance = SMSService::create_provider_instance($provider);
        if (is_object($provider_instance) && method_exists($provider_instance, 'query_balance')) {
            $out = $provider_instance->query_balance();
            $out = json_decode($out, true);
            if ($out['Success']) {
                $number = $out['Data'];
                if ($number <= $min_short_num) {
                    $provider_instance->send_msg($admin['phone'], $hint_configs['cfg_webname'], "短信已不足{$min_short_num}条，为避免对网站运营产生影响，请及时购买短信");
                }
            }

        }
    }

    public static function write_test()
    {
        file_put_contents(CACHE_DIR . 'crontest.txt', date('Y-m-d H:i:s') . "/r/n", FILE_APPEND);
    }

    public static function search_transfer_weixin() {
        Model_Member_Withdraw::search_transfer_weixin();
    }


}